package ink.tsg.springboot.service.impl;

import ink.tsg.springboot.entities.TbOrder;
import ink.tsg.springboot.entities.TbStock;
import ink.tsg.springboot.service.IRedisOversoldService;
import ink.tsg.springboot.service.ITbOrderService;
import ink.tsg.springboot.service.ITbStockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author geo_tsg
 * @version 1.0.0
 * @ClassName RedisOversoldServiceImpl.java
 * @Description
 * @createTime 2021-10-21
 */
@Service
public class RedisOversoldServiceImpl implements IRedisOversoldService {

    @Autowired
    private ITbOrderService orderService;

    @Autowired
    private ITbStockService stockService;
    //向上转型
    private Lock lock = new ReentrantLock();

    @Override
    public String buy(Integer id) {
        lock.lock();
        try {
            TbStock byId = stockService.getById(id);
            Integer num = byId.getStock() - 1;
            if (num < 0) {
                return "已售完！";
            }
            byId.setStock(num);
            TbOrder tbOrder = new TbOrder();
            tbOrder.setAmount(1);
            orderService.save(tbOrder);
            stockService.updateById(byId);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
        return "success";
    }
}
